package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nanchen.compresshelper.CompressHelper;
import com.revenant.driver.R;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.Driver.SearchEmptyBean;
import com.revenant.driver.bean.ShipperBean.FileUploadBean;
import com.revenant.driver.utils.GlideEngine;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.hutool.core.date.DateTime;

import static com.revenant.driver.utils.Constants.Driver_Car_Add;
import static com.revenant.driver.utils.Constants.UploadFile;

public class DriverIAddVetticalActivityThree extends BaseActivity {


    @BindView(R.id.upload_text_type)
    TextView uploadTextType;
    @BindView(R.id.upload_photo)
    ImageView uploadPhoto;
    @BindView(R.id.upload_type)
    Button uploadType;
    private String uploadurl = "";
    private List<LocalMedia> selectList = new ArrayList<>();
    private Context context;
    private String colorcode;
    private String energecode;
    private String oneurl;
    private String imageurltwo;
    private String cartypeid = "-1";

    @Override
    public int getContentViewResId() {
        return R.layout.activity_driver_add_vertical_three;
    }

    @Override
    public void initView() {
        context = this;


        Bundle bundle = getIntent().getExtras();
        colorcode = bundle.getString("colorCode");
        energecode = bundle.getString("energeCode");
        oneurl = bundle.getString("imageurlone");
        imageurltwo = bundle.getString("imageurltwo");
        cartypeid = bundle.getString("cartypeid");
        if (cartypeid.equals("-1")) {
            setcenterTitle("添加车辆");
        } else {
            setcenterTitle("修改车辆");
        }
    }

    @Override
    public void leftbarclick() {
        super.leftbarclick();
        finish();
    }

    @Override
    public void initData() {

    }

    private void getGoodsDetail(
            String vehiclePlateColorCode,
            String vehicleEnergyType,
            String drivingLicenseImgJust,
            String drivingLicenseImgBack,
            String operationCertificate
    ) {
        OkGo.<String>post(Driver_Car_Add)
                .headers("token", String.valueOf(System.currentTimeMillis()))
                .params("vehiclePlateColorCode", vehiclePlateColorCode)
                .params("vehicleEnergyType", vehicleEnergyType)
                .params("drivingLicenseImgJust", drivingLicenseImgJust)
                .params("drivingLicenseImgBack", drivingLicenseImgBack)
                .params("operationCertificate", operationCertificate)
                .params("accountId", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        SearchEmptyBean g = GsonUtil.parseJsonWithGson(response.body(), SearchEmptyBean.class);
                        if (g.getCode().equals("0")) {
                            showToast(g.getMsg());
                            finish();
                            startActivity(DriverVehicleManageActivity.class);
                        } else {
                            showToast(g.getMsg());
                            startActivity(DriverIAddVetticalActivity.class);
                            finish();
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private void updateGoodsDetail(
            String vehiclePlateColorCode,
            String vehicleEnergyType,
            String drivingLicenseImgJust,
            String drivingLicenseImgBack,
            String operationCertificate,
            String cartypeid
    ) {
        OkGo.<String>post(Driver_Car_Add)
                .headers("token", String.valueOf(System.currentTimeMillis()))
                .params("id", cartypeid)
                .params("vehiclePlateColorCode", vehiclePlateColorCode)
                .params("vehicleEnergyType", vehicleEnergyType)
                .params("drivingLicenseImgJust", drivingLicenseImgJust)
                .params("drivingLicenseImgBack", drivingLicenseImgBack)
                .params("operationCertificate", operationCertificate)
                .params("accountId", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        SearchEmptyBean g = GsonUtil.parseJsonWithGson(response.body(), SearchEmptyBean.class);
                        if (g.getCode().equals("0")) {
                            showToast(g.getMsg());
                            finish();
                            startActivity(DriverVehicleManageActivity.class);
                        } else {
                            showToast(g.getMsg());
                            startActivity(DriverIAddVetticalActivity.class);
                            finish();
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        if (!selectList.isEmpty()) {
                            showDig();
                            String url = media.getPath().startsWith("content://") ? media.getAndroidQToPath() : media.getPath();
                            uploadAvatar(url);
                        }
                    }
                    break;
            }
        }
    }


    private void uploadAvatar(final String path) {
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);

        OkGo.<String>post(UploadFile)
                .tag(this)
                .isMultipart(true)

                .params("file", newfile)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        if (response.code() == 200) {
                            FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                            if (fileUploadBean.getCode().equals("0")) {
                                uploadurl = fileUploadBean.getData().getUrl();
                                Glide.with(context).load(fileUploadBean.getData().getUrl()).centerCrop().
                                        into(uploadPhoto);
                            } else {
                                showToast(fileUploadBean.getMsg());
                            }
                        } else {
                            showToast(response.message());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.upload_photo, R.id.upload_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.upload_photo:
                showBottomSheetDialog(DriverIAddVetticalActivityThree.this);
//                PictureSelector.create(this)
//                        .openGallery(PictureMimeType.ofImage())
//                        .maxSelectNum(1)
//                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.upload_type:
                if (uploadurl.isEmpty()) {
                    showToast("请选择图片");
                } else {
                    if (cartypeid.equals("-1")) {
                        showDig();
                        getGoodsDetail(colorcode, energecode, oneurl, imageurltwo, uploadurl);
                    } else {
                        showDig();
                        updateGoodsDetail(colorcode, energecode, oneurl, imageurltwo, uploadurl, cartypeid);
                    }

                }
                break;
        }
    }
}
